package com.hudson.core.util;

import com.sun.tools.javac.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Author: 渔小鲤
 * @DateTime: 2025/7/15 23:03
 **/
public class PropertiesUtil {

    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    public static Properties getProperties(String propName) {
        return getProperties(propName, false);
    }

    public static Properties getProperties(String propName, boolean useExternalPath) {
        Properties prop = new Properties();

        String actualPath = propName;
        if (useExternalPath) {
            actualPath = "/app/" + propName;
        }

        try (InputStream inputStream = getResourceAsStream(actualPath)) {
            if (inputStream != null) {
                prop.load(inputStream);
            } else {
                logger.error("找不到配置文件: {}", actualPath);
            }
        } catch (IOException e) {
            logger.error("加载配置文件 {} 失败: {}", actualPath, e.getMessage());
        }

        return prop;
    }

    private static InputStream getResourceAsStream(String path) {
        // 首先尝试从classpath加载
        InputStream inputStream = Main.class.getClassLoader().getResourceAsStream(path);
        if (inputStream == null) {
            // 如果classpath中找不到，尝试从文件系统加载
            try {
                inputStream = new FileInputStream(path);
            } catch (FileNotFoundException e) {
                // 文件不存在，返回null
            }
        }
        return inputStream;
    }
}
